<?php

namespace app\common\model\xilujob;

use app\common\library\ScoreAction;
use think\Db;
use think\Log;
use think\Model;

class ResumeDownload extends Model
{

    protected $name = 'xilujob_resume_download';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = false;

    public function company() {
        return $this->belongsTo('CompanyProfile','company_id','id',[],'LEFT');
    }

    public function companyStatistics() {
        return $this->belongsTo('CompanyStatistics','company_id','id',[],'LEFT');
    }

    public function resume() {
        return $this->belongsTo('Resume','resume_id')->setEagerlyType(0);
    }

    /**
     * 公司下载简历
     * @param CompanyProfile|int $user 公司的user
     * @param $resume
     * @param bool $isApplicant
     * @return string|Model
     */
    public static function downloadResume($companyId, $resume) {
        if(!$resume instanceof Resume) {
            $resume = Resume::get($resume);
        }
        $model = static::where('company_id', $companyId)->where('resume_id',$resume->id)->find();
        if($model) {
            return $model;
        }
        Db::startTrans();
        try {
            $model = new static(['company_id'=>$companyId,'user_id'=>$resume->user_id,'resume_id'=>$resume->id]);
            if(!$model->save()) {
                throw new \LogicException($model->getError());
            }
            $resume->save(['download_count'=>Db::raw('download_count+1')]);

            //更新企业简历下载数
            CompanyStatistics::where('id', $companyId)->update(['resume_download_count'=>Db::raw('resume_download_count+1')]);

            Db::commit();
            return $model;
        }catch (\Exception $e) {
            Db::rollback();
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            return $e->getMessage();
        }

    }

}
